#include <wsnos.h>

static list_head_t eblock_list_head;

#ifdef OSEL_EBLOCK_DEBUG
static osel_uint8_t g_osel_maxeblock_cnt = 0;   	
static osel_uint8_t g_osel_eblock_cnt = 0;			
#endif

osel_bool_t osel_eblock_init(osel_uint32_t block_cnts)
{
	event_block_t *eblock = OSEL_NULL;
	osel_uint8_t i =0;

	list_init(&eblock_list_head);
	
	eblock = (event_block_t *)osel_mem_alloc(sizeof(event_block_t) * block_cnts);
	OSEL_ASSERT(eblock != OSEL_NULL);

	if(eblock == OSEL_NULL)
	{
		return OSEL_FALSE;
	}
	for(i = 0; i< block_cnts; i++)
	{
		list_append(&(eblock + i)->list, &eblock_list_head); 
	}
	
    return OSEL_TRUE;
}

event_block_t *osel_eblock_malloc(_EBLOCK_LINE1_)
{
	event_block_t *eblock = OSEL_NULL;
	OSEL_INT_LOCK();
	eblock = list_entry_decap(&eblock_list_head, event_block_t, list); 
	OSEL_INT_UNLOCK();

	if(eblock != OSEL_NULL)
	{
		osel_memset((event_pool_t *)eblock, 0,sizeof(event_pool_t));
		list_init(&(eblock->list));
		#ifdef OSEL_EBLOCK_DEBUG
		OSEL_INT_LOCK();
		eblock->alloc_line = line;

		if(g_osel_maxeblock_cnt < ++g_osel_eblock_cnt)
		{
			g_osel_maxeblock_cnt = g_osel_eblock_cnt;
		}
		OSEL_INT_UNLOCK();
		#endif
	}

	return eblock;
}

void osel_eblock_free(event_block_t **eblock _EBLOCK_LINE2_)
{
	OSEL_ASSERT(*eblock != OSEL_NULL);
	if(*eblock == OSEL_NULL)
	{
		return;
	}

	#ifdef OSEL_EBLOCK_DEBUG
	OSEL_INT_LOCK();
	g_osel_eblock_cnt--;
	OSEL_INT_UNLOCK();
	#endif

	osel_memset((event_pool_t *)(*eblock), 0, sizeof(event_pool_t));

	#ifdef OSEL_EBLOCK_DEBUG
	OSEL_INT_LOCK();
	(*eblock)->free_line = line;
	OSEL_INT_UNLOCK();
	#endif

	OSEL_INT_LOCK();
	list_append(&((*eblock)->list), &eblock_list_head);	
	OSEL_INT_UNLOCK();

	*eblock = OSEL_NULL;
}



